package br.brpv.silvestrin.vendas.settingsactivity;


import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import br.brpv.silvestrin.vendas.R;
import br.brpv.silvestrin.vendas.util.ShowMessage;
import br.brpv.silvestrin.vendas.webservice.ServerConnection;
import br.brpv.silvestrin.vendas.listeners.ValidateWSListener;

/**
 * Created with IntelliJ IDEA.
 * User: paulo
 * Date: 4/19/12
 * Time: 4:53 PM
 * To change this template use File | Settings | File Templates.
 */
public class SettingsWebserviceFragment extends Fragment implements ValidateWSListener {

    public static final String WEB_SERVICE_PREFERENCES = "web_service_preferences";

    public static final String SERVER_NAME = "server_name";
    public static final String SERVER_URL = "url";
    public static final String SERVER_USER = "server_user";
    public static final String SERVER_PASSWORD = "password";

    private Activity activity = null;
    private ValidateWSListener callbackListener = this;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v;

        v = inflater.inflate(R.layout.settings_webservice, container, false);

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);    //To change body of overridden methods use File | Settings | File Templates.
        activity = getActivity();

        loadServerParameters();

        Button saveButton = (Button)activity.findViewById(R.id.server_save);
        saveButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                EditText serverUrl = (EditText)activity.findViewById(R.id.server_url);
                ServerConnection.validateServer(serverUrl.getText().toString(), callbackListener);

            }
        });


    }

    public static SettingsWebserviceFragment newInstance(int index) {
        SettingsWebserviceFragment f = new SettingsWebserviceFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    private void saveServerParameters(){
        SharedPreferences preferences = activity.getSharedPreferences(WEB_SERVICE_PREFERENCES, Activity.MODE_WORLD_WRITEABLE);
        SharedPreferences.Editor editor = preferences.edit();

        EditText serverName = (EditText)activity.findViewById(R.id.server_name);
        editor.putString(SERVER_NAME, serverName.getText().toString());

        EditText serverUrl = (EditText)activity.findViewById(R.id.server_url);
        editor.putString(SERVER_URL, serverUrl.getText().toString());

        EditText serverUser = (EditText)activity.findViewById(R.id.server_user);
        editor.putString(SERVER_USER, serverUser.getText().toString());

        EditText serverPass = (EditText)activity.findViewById(R.id.server_password);
        editor.putString(SERVER_PASSWORD, serverPass.getText().toString());

        editor.commit();

        activity.findViewById(R.id.server_save).setEnabled(false);
    }
    private void loadServerParameters(){
        activity = getActivity();
        SharedPreferences preferences = activity.getSharedPreferences(WEB_SERVICE_PREFERENCES, Activity.MODE_WORLD_READABLE);

        //if user change some settings parameters enable save button
        TextWatcher watcher = new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Button saveButton = (Button)activity.findViewById(R.id.server_save);
                saveButton.setEnabled(true);
            }

            public void afterTextChanged(Editable editable) {
            }
        };

        EditText serverName = (EditText)activity.findViewById(R.id.server_name);
        serverName.setText(preferences.getString(SERVER_NAME,"Silvestrin_test"));
        serverName.addTextChangedListener(watcher);

        EditText serverUrl = (EditText)activity.findViewById(R.id.server_url);
        serverUrl.setText(preferences.getString(SERVER_URL,"http://200.174.161.8:8090/FullWSG/service.asmx"));
        serverUrl.addTextChangedListener(watcher);

        EditText serverUser = (EditText)activity.findViewById(R.id.server_user);
        serverUser.setText(preferences.getString(SERVER_USER, "silvestrin"));
        serverUser.addTextChangedListener(watcher);

        EditText serverPass = (EditText)activity.findViewById(R.id.server_password);
        serverPass.setText(preferences.getString(SERVER_PASSWORD, "colsilves@."));
        serverPass.addTextChangedListener(watcher);
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

	public void onValidateServer(boolean valid) {
        if(valid) {
            //EditText serverUrl = (EditText)activity.findViewById(R.id.server_url);
            EditText serverUser = (EditText)activity.findViewById(R.id.server_user);
            EditText serverPass = (EditText)activity.findViewById(R.id.server_password);

            ServerConnection.validateUser(serverUser.getText().toString(), serverPass.getText().toString(), callbackListener);
        }
        else {
            ShowMessage.alertDialog(getActivity(), R.string.settings_server_unreachable);
        }
	}

	public void onValidateUser(boolean valid) {
        if(valid) {
            saveServerParameters();
        } else {
            ShowMessage.alertDialog(getActivity(), R.string.settings_user_password_invalid);
        }
	}
}